package com.zeny.coding.interceptors;

import com.alibaba.fastjson.JSON;
import com.zeny.coding.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;

/**
 * <h2>TODO</h2>
 *
 * @Author Zeny
 */
@SuppressWarnings("all")
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        log.info("uri: {}", uri);
        //请求地址中不包含/admin/的，不是后台管理系统的请求，不需要拦截
        if (!uri.contains("/admin/")) {
            return true;
        }
        if (uri.contains("/system/admin/user/login")
                || uri.contains("/system/admin/user/logout")
                || uri.contains("/system/admin/kaptcha")) {
            log.info("不需要控台登录验证：{}", uri);
            return true;
        }
        String token = request.getHeader("token");
        log.info("控台登录验证开始，token：{}", token);
        if (StringUtils.isEmpty(token)) {
            log.info("token为空，请求被拦截");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        String userMsg = (String) redisTemplate.opsForValue().get(token);
        UserDto userDto = JSON.parseObject(userMsg, UserDto.class);
        if (userDto == null) {
            log.warn("token无效，请求被拦截");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        } else {
            log.info("已登录, 用户信息：{}", userDto);
            log.info("接口权限校验，请求地址：{}", uri);
            boolean exist = false;
            HashSet<String> requests = userDto.getRequests();
            // 遍历所有【权限请求】，判断当前请求的地址是否在【权限请求】里
            for (String req : requests) {
                if (uri.contains(req)) {
                    exist = true;
                    break;
                }
            }
            if (exist) {
                log.info("权限校验通过");
                return true;
            } else {
                log.warn("权限校验未通过");
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            }
        }
    }
}
